<?php

namespace app\resources\model;

use help\EncryptionHelp;

class UserFrp extends BaseModel
{
    
    const DIRECTORY = '/usr/frps/config';     // 目录

    // 写入前
    public static function onBeforeWrite($data)
    {
        if( ($data['nid'] ?? 0) ){
            $node = Nodes::find($data['nid']);
            if($node){
                $data['server_addr'] = $data['server_addr'] ?? $node->host;
                $data['server_port'] = $data['server_port'] ?? $node->getProt();
            }
        }
        $data['http_port'] = ($data['server_port'] ?? Nodes::MIN_PROT) + 1;
        $data['token'] = $data['token'] ?? self::getSecretKey();
    }
    
    /**
     * 获取密钥
     * @return void
     */
    public static function getSecretKey(){
        return EncryptionHelp::encryptString( EncryptionHelp::makeEncrypt() ,'frps');
    }

    /**
     * 解密密钥
     * @return void
     */
    public static function decryptSecretKey($encrypt){
        return EncryptionHelp::decryptString($encrypt?:'','frps');
    }

    /**
     * 获取文件名称
     * @return void
     */
    public function fileName(){
        return $this->id.'-'.$this->server_port.'-'.$this->http_port.'.ini';;
    }

    // 一对多关联 - 节点
    public function node()
    {
    	return $this->hasMany(Nodes::class,'nid','nid');
    }

}